package com.infosystem.demo.services;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.aliyun.oss.OSS;
import com.infosystem.demo.config.OssConfig;
import com.infosystem.demo.config.FileType;

import com.infosystem.demo.entities.Employee;
import com.infosystem.demo.entities.Resume;
import com.infosystem.demo.models.EmployeeDTOI;
import com.infosystem.demo.repositories.EmployeeRepository;
import com.infosystem.demo.repositories.ResumeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.DataSource;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * derived from example from @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@Service("fileUploadService")
public class FileService {
    @Autowired
    private OSS ossClient;
    @Autowired
    private OssConfig ossConfig;

    public String ossUploadFile(MultipartFile uploadFile, String uploadType) {
        String fileHost = uploadType;
        //校验文件类型
        String fileType = "";
        Boolean isLeagal = true;
        // get original file name
        String fileName = uploadFile.getOriginalFilename();
        for (FileType type : FileType.values()) {
            if (fileName.endsWith(type.getType())) {
                fileType = type.getType();
                break;
            }
        }
        // if no extension
        if (fileType.equals("")){
            isLeagal = false;
        }

        if (!isLeagal){
            return null;
        }

        // set upload file name
        String upLoadUrl = fileHost + "/" + fileName;
        // set return URL
        String returnUrl = "";

        //read file content
        //input stream
        InputStream inputStream = null;
        try {
            //assign the file's IS to the input stream
            inputStream = uploadFile.getInputStream();
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }

        /*
         * https://developer.aliyun.com/article/828637
         * 现在阿里云OSS 默认图片上传ContentType是image/jpeg
         * 也就是说，获取图片链接后，图片是下载链接，而并非在线浏览链接，
         * 因此，这里在上传的时候要解决ContentType的问题，将其改为image/jpg
         */

        // ObjectMetadata meta = new ObjectMetadata();
        // meta.setContentType("image/jpg");

        //IMPORTANT: upload file to oss
        try{
            ossClient.putObject(OssConfig.bucketName, upLoadUrl, inputStream);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        ossClient.shutdown();

        // get file url
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        returnUrl = ossClient.generatePresignedUrl(OssConfig.bucketName, fileName, expiration).toString();
        return returnUrl;
    }

    /** Upload file to local dir
     * @param uploadFile
     * @param uploadType
     * @return file url
     */
    public String uploadToLocal(MultipartFile uploadFile, String uploadType) {
        if (uploadFile.isEmpty()) {
            System.out.println("The file is empty!");
            return null;
        }
        try {
            // get original file name
            String fileName = uploadFile.getOriginalFilename();
            // set upload file name, relative path
            String upLoadUrl = uploadType + "/" + fileName;

            byte[] bytes = uploadFile.getBytes();
            File uploadedFile = new File(upLoadUrl);
            uploadFile.transferTo(uploadedFile);
            return upLoadUrl;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public ResponseEntity<Resource> downloadFromLocal(String uploadUrl){
        Path targetPath = Paths.get(uploadUrl);
        try{
            Resource resource = new org.springframework.core.io.UrlResource(targetPath.toUri());
            if (resource.exists() || resource.isReadable()){
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }


}